package com.startest.sms.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * Created by cly on 2018/12/3.
 * 验证码图片生成器
 *
 */
public class PictureCaptcha {
    private final static int textLength = 4;
    private int width = 120;
    private int height = 40;
    private Random random = new Random();
    private String[] fontName = {"Cambria", "华文楷体", "Consolas", "微软雅黑", "楷体_GB2312"};
    private String codes = "23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYXZ";
    private Color color = new Color(255,255,255);
    private String text;

    //随机颜色
    private Color randomColor(){
        int r = random.nextInt(150);
        int g = random.nextInt(150);
        int b = random.nextInt(150);
        return new Color(r,g,b);
    }

    //随机字体
    private Font randomFont(){
        int index = random.nextInt(fontName.length);
        String fontname = fontName[index];
        int style = random.nextInt(4);
        int size = random.nextInt(5) + 24;
        return new Font(fontname,style,size);
    }

    //随机字符
    private char randomChar(){
        int index = random.nextInt(codes.length());
        return codes.charAt(index);
    }

    //创建图片
    private BufferedImage createImage(){
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = (Graphics2D) bufferedImage.getGraphics();
        graphics2D.setColor(this.color);//背景色
        graphics2D.fillRect(0,0,width,height);//画刷填充
        return bufferedImage;
    }

    //创建验证码（图片+文字）
    public BufferedImage getCaptcha(){
        BufferedImage image = createImage();
        Graphics2D graphics2D = (Graphics2D) image.getGraphics();
        StringBuilder stringBuilder = new StringBuilder();
        for(int i=0;i<textLength;i++){
            String s = String.valueOf(randomChar());
            stringBuilder.append(s);
            float x = i*1.0F*width/textLength;//设置x轴坐标
            graphics2D.setFont(randomFont());
            graphics2D.setColor(randomColor());
            graphics2D.drawString(s,x,height-5);
        }
        this.text = stringBuilder.toString();
        //干扰线

        return image;
    }

    //获取文本
    public String getText(){
        return text;
    }

    //获取输出
    public void output(BufferedImage bufferedImage, OutputStream outputStream) throws IOException {
        ImageIO.write(bufferedImage,"JPEG",outputStream);
    }

}
